<template>
  <div>
    <Card :bordered="false" dis-hover class="ivu-mt box">
      <Form
        ref="formValidate"
        :model="formValidate"
        :label-width="labelWidth"
        :label-position="labelPosition"
        @submit.native.prevent
      >
        <FormItem :label="$t('page.stock.select_date')+'：'">
          <DatePicker
            :editable="false"
            :clearable="true"
            @on-change="onchangeTime"
            :value="timeVal"
            format="yyyy/MM/dd"
            type="datetimerange"
            placement="bottom-start"
            style="width: 250px"
            :options="options"
          >
          </DatePicker>
        </FormItem>
      </Form>
    </Card>

    <Card :bordered="false" dis-hover class="ive-mt tablebox">
      <div class="product_tabs tabbox">
        <Tabs @on-click="onClickTab">
          <TabPane label="仓储列表" name="month" />
        </Tabs>
      </div>
      <div class="btnbox"></div>
      <div class="table">
        <Table
          :columns="columns"
          :data="orderList"
          ref="table"
          class="mt25"
          :loading="loading"
          highlight-row
          no-userFrom-text="暂无数据"
          no-filtered-userFrom-text="暂无筛选结果"
        >
          <template slot-scope="{ row, index }" slot="income_num">
            <span style="color: #f5222d">￥{{ row.income_num }}</span>
          </template>
          <template slot-scope="{ row, index }" slot="exp_num">
            <span style="color: #00c050">￥{{ row.exp_num }}</span>
          </template>
          <template slot-scope="{ row, index }" slot="pay_price">
            <span>${{ row.pay_price }}</span>
          </template>
          <template slot-scope="{ row, index }" slot="action">
            <a @click="Info(row)">账单详情</a>
            <a @click="exportBili(row.id)">下载</a>
          </template>
        </Table>
        <div class="acea-row row-right page">
          <Page
            :total="total"
            :current.sync="formValidate.page"
            @on-change="pageChange"
            :page-size="formValidate.limit"
          />
        </div>
      </div>
    </Card>
    <warehouse-detail ref="commission"></warehouse-detail>
  </div>
</template>

<script>
import exportExcel from '@/utils/newToExcel.js';
import warehouseDetail from '../components/warehouseDetail';
import {storeWarehouseBillList, exportfundRecordApi, exportWarehouseBillInfo} from '@/api/capital';
import timeOptions from '@/utils/timeOptions2';
import {supplier} from "@api/setting";
import {exportSupplierSummaryInfo} from "@api/finance";
export default {
  name: 'bill',
  components: {
    warehouseDetail,
  },
  data() {
    return {
      total: 0,
      loading: false,
      tab: 'day',
      options: timeOptions,
      columns: [
        {
          title: 'ID',
          key: 'id',
          width: 60,
        },
        {
          title: '账单名称',
          key: 'name',
          minWidth: 200,
        },
        {
          title: '金额',
          key: 'amount',
          minWidth: 80,
        },
        {
          title: '时间',
          key: 'time',
          minWidth: 80,
        },
        {
          title: '操作',
          slot: 'action',
          fixed: 'right',
          minWidth: 120,
          align: 'center',
        },
      ],
      orderList: [],
      formValidate: {
        data: '',
        page: 1,
        limit: 20,
      },
      timeVal: [],
      system_supplier:{},
      fromList: {
        title: '选择时间',
        custom: true,
        fromTxt: [
          { text: '全部', val: '' },
          { text: '昨天', val: 'yesterday' },
          { text: '今天', val: 'today' },
          { text: '本周', val: 'week' },
          { text: '本月', val: 'month' },
          { text: '本季度', val: 'quarter' },
          { text: '本年', val: 'year' },
        ],
      },
    };
  },
  computed: {
    labelWidth() {
      return this.isMobile ? undefined : 80;
    },
    labelPosition() {
      return this.isMobile ? 'top' : 'left';
    },
  },
  watch: {
    tab: {
      handler() {
        this.getList();
        this.getInfo();
      },
      immediate: true,
    },
  },
  methods: {
    async exportBili(id) {
      try {
        this.loading = true;
        let res; // 在函数作用域声明
        // 1. 调用导出接口获取文件信息
        res = await exportWarehouseBillInfo(id);
        // 2. 检查响应是否成功
        if (res.code !== 0) {
          throw new Error(res.msg || '导出失败');
        }

        // 3. 获取文件信息
        const fileInfo = res.data;

        // 4. 使用文件URL下载文件
        await this.downloadFile(fileInfo);

        // 5. 显示成功消息
        this.$Message.success('导出成功，文件已开始下载');

      } catch (error) {
        // 错误处理
        this.$Message.error(error.message || '导出失败，请重试');
        console.error('导出错误:', error);
      } finally {
        this.loading = false;
      }
    },
    async downloadFile(fileInfo) {
      try {
        // 1. 创建下载链接（优先使用 download_url，再使用 exports_url）
        // const downloadUrl = fileInfo.download_url || fileInfo.exports_url;
        const downloadUrl = fileInfo.exports_url;
        // 2. 创建隐藏的<a>标签触发下载
        const link = document.createElement('a');
        link.href = downloadUrl;

        // 从URL中提取文件名，或自定义文件名
        const fileName = downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1);
        link.download = fileName; // 设置下载文件名

        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        console.error('文件下载错误:', error);
        throw new Error('文件下载失败: ' + error.message);
      }
    },
    onClickTab(e) {
      this.tab = e;
    },
    getList() {
      this.loading = true;
      let data = {
        timeType: this.tab,
        data: this.formValidate.data,
        page: this.formValidate.page,
        limit: this.formValidate.limit,
      };
      storeWarehouseBillList(data).then((res) => {
        this.orderList = res.data.list;
        this.loading = false;
        this.total = res.data.count;
      });
    },
    // 选择时间
    selectChange(tab) {
      this.formValidate.page = 1;
      this.formValidate.data = tab;
      this.timeVal = [];
      this.getList();
    },
    // 具体日期
    onchangeTime(e) {
      this.timeVal = e;
      this.formValidate.data = this.timeVal[0] ? this.timeVal.join('-') : '';
      this.formValidate.page = 1;
      this.getList();
    },
    //分页
    pageChange(status) {
      this.formValidate.page = status;
      this.getList();
    },
    getInfo(){
      supplier().then(res=>{
        this.system_supplier = res.data.info
      }).catch(err=>{
        this.$Message.error(err.msg);
      })
    },
    // 账单详情
    Info(row) {

      this.$refs.commission.modals = true;
      this.$refs.commission.warehouse_type = this.system_supplier.warehouse_type
      this.$refs.commission.supplier_type = this.system_supplier.type
      this.$refs.commission.getList(row.id);
    },
    //下载
    async download(row) {
      let [th, filekey, data, fileName] = [[], [], [], ''];
      let excelData = { ids: row.ids, page: 1 };
      let lebData = await this.getExcelData(excelData);
      if (!fileName) {
        fileName = lebData.filename;
      }
      if (!filekey.length) {
        filekey = lebData.filekey;
      }
      if (!th.length) {
        th = lebData.header;
      }
      data = [...data, ...lebData.export];
      exportExcel(th, filekey, fileName, data);
    },
    getExcelData(excelData) {
      return new Promise((resolve) =>
        exportfundRecordApi(excelData).then((res) => resolve(res.data))
      );
    },
  },
};
</script>

<style scoped lang="less">
/deep/.ivu-page-header,
/deep/.ivu-tabs-bar {
  border-bottom: 1px solid #ffffff;
}
/deep/.ivu-card-body {
  padding: 0;
}
/deep/.ivu-tabs-nav {
  height: 45px;
}

/deep/.ivu-tabs-bar {
  margin-bottom: 0px !important;
  border-bottom: 1px solid #e9e9e9 !important;
}
.tabbox {
  padding: 16px 20px 0px;
}
.box {
  padding: 20px;
  padding-bottom: 1px;
}
.tablebox {
  margin-top: 15px;
  padding-bottom: 10px;
}
.btnbox {
  padding: 20px 0px 0px 30px;
  .btns {
    width: 99px;
    height: 32px;
    background: #1890ff;
    border-radius: 4px;
    text-align: center;
    line-height: 32px;
    color: #ffffff;
    cursor: pointer;
  }
}
.table {
  padding: 0px 30px 15px 30px;
}
</style>
